﻿using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Threading;
using System.Net.Mail;
using System.Net;

/// <summary>
/// Fun 的摘要说明
/// </summary>
public class Fun
{
    public Fun()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    public static void Start()
    {
        Fun.SetIntervalFunc();
    }

    public static int Guid()
    {
        string sql = "insert into Guid(CreateDate) values('"+DateTime.Now.ToString()+"')";
        return Fun.Insert(sql);
    }

    public static void SetIntervalFunc()
    {
        Params.WaitMilliSeconds = 0;
        int nh = DateTime.Now.Hour;
        int wm = 0;
        if (nh < 3)
        {
            wm = (3 - nh) * Params.HourMilliSeconds;
        }
        else
        {
            wm = (nh - 3) * Params.HourMilliSeconds;
        }
        Params.WaitMilliSeconds = wm;
        ThreadStart its = new ThreadStart(IntervalFunc);
        Thread it = new Thread(its);
        it.Name = "TimerFuncs";
        it.Start();
    }

    public static void IntervalFunc()
    {
        System.Threading.Thread.Sleep(Params.WaitMilliSeconds);
        Fun.TimerFuncs();
        while (true)
        {
            System.Threading.Thread.Sleep(Params.DayMilliSeconds);
            Fun.TimerFuncs();
        }
    }

    public static void TimerFuncs()
    {
        Fun.ClearTempNews();
        Fun.ClearTempFolder();
    }

    public static void ClearTempNews()
    {
        string sql = "select FileName from tZ_NewsFile where NewsID in (select IndexID from tZ_News where Valid=0)";
        DataTable dt = Fun.CreateDt(sql);
        foreach (DataRow dr in dt.Rows)
        {
            string fn = dr["0"].ToString().Trim();
            string fp = Params.FilesFolderPath + fn;
            Fun.DeleteFile(fp);
        }
        sql = "select FileName from tZ_NewsPhoto where NewsID in (select IndexID from tZ_News where Valid=0)";
        dt = Fun.CreateDt(sql);
        foreach (DataRow dr in dt.Rows)
        {
            string fn = dr["0"].ToString().Trim();
            string fp = Params.FilesFolderPath + fn;
            Fun.DeleteFile(fp);
        }
        sql = "delete from tZ_News where Valid=0";
        Fun.Execute(sql);
    }

    public static void ClearTempFolder()
    {
        if (System.IO.Directory.Exists(Params.TmpFolderPath))
        {
            try
            {
                System.IO.Directory.Delete(Params.TmpFolderPath, true);
            }
            catch
            {
            }
        }
        if (!System.IO.Directory.Exists(Params.TmpFolderPath))
        {
            System.IO.Directory.CreateDirectory(Params.TmpFolderPath);
        }
    }


    public static object GetField(string sql, string field)
    {
        DataView dv = new DataView();
        Params.oPro.CreateDV(Params.Conn, sql, "", ref dv);
        if (dv.Table.Rows.Count < 1)
            return null;
        return dv.Table.Rows[0][0];
    }


    public static object GetField(string sql)
    {
        return Fun.GetField(sql, "n");
    }

    public static int InsertAndGetMaxID(string sql, string tab, string field)
    {
        int r = Params.oPro.Execute(Params.Conn, sql);
        if (r < 1)
        {
            return -1;
        }
        string sql2 = "select max(" + field + ") as znum from " + tab;
        int n = Convert.ToInt32(Fun.GetField(sql2, field));
        return n;
    }

    public static int InsertLog(string l)
    {
        int g=Fun.Guid();
        string sql = "insert into tZ_Log(Guid,WebLog) values("+g.ToString()+",'" + l.Replace("'", "''") + "')";
        Params.oPro.Execute(Params.Conn, sql);
        return g;
    }

    public static DataTable CreateDtFromExcel(string f)
    {
        string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + f + ";Extended Properties='Excel 8.0;IMEX=1'";
        OleDbConnection myConn = new OleDbConnection(strCon);
        myConn.Open();
        DataTable sheetable = myConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "Table" });
        string sheetname = sheetable.Rows[0][2].ToString();
        string strCom = " SELECT * FROM [" + sheetname + "] ";
        OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
        DataSet myDataSet = new DataSet();
        myCommand.Fill(myDataSet, "[" + sheetname + "]");
        myConn.Close();
        DataTable dt = myDataSet.Tables[0];
        return dt;
    }

    public static string GetFileName()
    {
        DateTime dt = DateTime.Now;
        return dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString() + Params.MyRandom.Next().ToString();
    }

    public static string CutStr(string str, int length)
    {
        /*
        if (str.Length <= length)
        {
            return str;
        }
        string s = str.Substring(0, length) + "...";
        return s;
         * */
        return Fun.CutStr(str, length, "...");
    }

    public static string CutStr(string s, int l, string endStr)
    {
        string temp = s.Substring(0, (s.Length < l + 1) ? s.Length : l + 1);
        byte[] encodedBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(temp);

        string outputStr = "";
        int count = 0;

        for (int i = 0; i < temp.Length; i++)
        {
            if ((int)encodedBytes[i] == 63)
                count += 2;
            else
                count += 1;

            if (count <= l - endStr.Length)
                outputStr += temp.Substring(i, 1);
            else if (count > l)
                break;
        }

        if (count <= l)
        {
            outputStr = temp;
            endStr = "";
        }

        outputStr += endStr;

        return outputStr;
    }

    public bool IsNumber(String strNumber)
    {
        Regex objNotNumberPattern = new Regex("[^0-9.-]");
        Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
        Regex objTwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*");
        String strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
        String strValidIntegerPattern = "^([-]|[0-9])[0-9]*$";
        Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")");

        return !objNotNumberPattern.IsMatch(strNumber) &&
        !objTwoDotPattern.IsMatch(strNumber) &&
        !objTwoMinusPattern.IsMatch(strNumber) &&
        objNumberPattern.IsMatch(strNumber);
    }


    public static bool IsNumeric(string value)
    {
        return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");
    }
    public static bool IsInt(string value)
    {
        return Regex.IsMatch(value, @"^[+-]?\d*$");
    }
    public static bool IsUnsign(string value)
    {
        return Regex.IsMatch(value, @"^\d*[.]?\d*$");
    }

    public static DataView CreateDV(string sql)
    {
        DataView dv = new DataView();
        Params.oPro.CreateDV(Params.Conn, sql, "", ref dv);
        return dv;
    }

    public static DataTable CreateDt(string sql)
    {
        DataView dv = new DataView();
        Params.oPro.CreateDV(Params.Conn, sql, "", ref dv);
        DataTable dt = dv.Table;
        return dt;
    }

    public static DataRow CreateDr(string sql)
    {
        DataView dv = CreateDV(sql);
        if (dv.Table.Rows.Count < 1)
        {
            return null;
        }
        DataRow dr = dv.Table.Rows[0];
        return dr;
    }

    public static int Execute(string sql)
    {
        return Params.oPro.Execute(Params.Conn, sql);
    }

    public static int Insert(string sql)
    {
        string s = sql + " SELECT @@IDENTITY AS v";
        return Convert.ToInt32(Fun.GetField(s, "v"));
    }

    public static string GetImgUrl(string HTMLStr)
    {
        string str = "";
        //string sPattern = @"^<img\s+[^>]*>";
        Regex r = new Regex(@"<img\s+[^>]*\s*src\s*=\s*([']?)(?<url>\S+)'?[^>]*>",
                RegexOptions.Compiled);
        Match m = r.Match(HTMLStr.ToLower());
        if (m.Success)
            str = m.Result("${url}");
        return str;
    }

    public static string GetRandomString(int len, bool alpha)
    {
        int l = Params.Alpha.Length;
        string str = "";
        for (int i = 0; i < len; i++)
        {
            int n;
            if (alpha)
            {
                n = Params.MyRandom.Next(61);
            }
            else
            {
                n = Params.MyRandom.Next(l);
            }
            str = str + Params.Alpha[n];
        }
        return str;
    }

    public static string GetRandomString(int len, int alphaLen)
    {
        string str = "";
        for (int i = 0; i < len; i++)
        {
            int n;
            n = Params.MyRandom.Next(alphaLen - 1);
            str = str + Params.Alpha[n];
        }
        return str;
    }

    public static string GetRandomString(int len)
    {
        return Fun.GetRandomString(len, false);
    }

    public static DateTime DateSelectorFormat(string s)
    {
        if (s == "" || s == null)
        {
            return DateTime.Now;
        }
        DateTime d;
        try
        {
            d = DateTime.Parse(s);
        }
        catch
        {
            d = DateTime.Now;
        }
        return d;
    }

    public static string NumToUpper(int n, bool b)
    {
        if (n < 0)
        {
            return "";
        }
        string s = n.ToString();
        s = s.Replace("0", "零");
        s = s.Replace("1", "一");
        s = s.Replace("2", "二");
        s = s.Replace("3", "三");
        s = s.Replace("4", "四");
        s = s.Replace("5", "五");
        s = s.Replace("6", "六");
        s = s.Replace("7", "七");
        s = s.Replace("8", "八");
        s = s.Replace("9", "九");
        if (!b)
        {
            return s;
        }
        int l = s.Length;
        if (l == 2 && s[0] == '一')
        {
            return "十" + s[1];
        }
        if (l >= 2)
        {
            s = s.Insert(l - 1, "十");
        }
        l = s.Length;
        if (l >= 3 + 1)
        {
            s = s.Insert(l - 2 - 1, "百");
        }
        l = s.Length;
        if (l >= 4 + 2)
        {
            s = s.Insert(l - 3 - 2, "千");
        }
        l = s.Length;
        if (s[l - 1] == '零')
        {
            s = s.Remove(l - 1);
        }
        return s;
    }

    public static bool DeleteFile(string fp)
    {
        if (System.IO.File.Exists(fp))
        {
            System.IO.File.Delete(fp);
        }
        return !System.IO.File.Exists(fp);
    }

    public static bool StringContains(string[] ary, string s)
    {
        int c = ary.Length;
        for (int i = 0; i < c; i++)
        {
            if (ary[i] == s)
            {
                return true;
            }
        }
        return false;
    }

    public static string ReplaceHtmlTag(string html)
    {
        return html.Replace(" ", "&nbsp;").Replace("\n", "<br/>").Replace("<", "&lt;").Replace(">", "&gt;");
    }

    public static bool SendMail(string StrTo, string StrBody, string strSubjec)
    {
        MailMessage onemail = new MailMessage();
        string myEmail = Params.SmtpUser; //发送邮件的邮箱地址
        string myPwd = Params.SmtpPassword; //发送邮件的邮箱密码
        onemail.BodyEncoding = System.Text.Encoding.UTF8;
        onemail.IsBodyHtml = true;
        onemail.From = new MailAddress(myEmail);
        onemail.To.Add(new MailAddress(StrTo));
        onemail.Subject = strSubjec;
        onemail.Body = StrBody;
        SmtpClient clint = new SmtpClient(Params.SmtpHost, Params.SmtpPort);//发送邮件的服务器
        clint.Credentials = new System.Net.NetworkCredential(myEmail, myPwd);
        clint.EnableSsl = true;
        clint.Timeout = 15000;
        try { clint.Send(onemail); }
        catch { return false; }
        return true;
    }

    public static void ExportExcel(ref DataSet ds, string fp)
    {
        Fun.DeleteFile(fp);
        StreamWriter sw = new StreamWriter(fp, false);
        sw.WriteLine("<?xml version=\"1.0\"?>");
        sw.WriteLine("<?mso-application progid=\"Excel.Sheet\"?>");
        sw.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
        sw.WriteLine(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
        sw.WriteLine(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
        sw.WriteLine(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
        sw.WriteLine(" xmlns:html=\"http://www.w3.org/TR/REC-html40\">");
        sw.WriteLine(" <DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">");
        sw.WriteLine("  <Author>Automated Report Generator Example</Author>");
        sw.WriteLine(string.Format("  <Created>{0}T{1}Z</Created>", DateTime.Now.ToString("yyyy-mm-dd"), DateTime.Now.ToString("HH:MM:SS")));
        sw.WriteLine("  <Company>Matteo</Company>");
        sw.WriteLine("  <Version>11.6408</Version>");
        sw.WriteLine(" </DocumentProperties>");
        sw.WriteLine(" <ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">");
        sw.WriteLine("  <WindowHeight>8955</WindowHeight>");
        sw.WriteLine("  <WindowWidth>11355</WindowWidth>");
        sw.WriteLine("  <WindowTopX>480</WindowTopX>");
        sw.WriteLine("  <WindowTopY>15</WindowTopY>");
        sw.WriteLine("  <ProtectStructure>False</ProtectStructure>");
        sw.WriteLine("  <ProtectWindows>False</ProtectWindows>");
        sw.WriteLine(" </ExcelWorkbook>");
        sw.WriteLine(" <Styles>");
        sw.WriteLine("  <Style ss:ID=\"Default\" ss:Name=\"Normal\">");
        sw.WriteLine("   <Alignment ss:Vertical=\"Bottom\"/>");
        sw.WriteLine("   <Borders/>");
        sw.WriteLine("   <Font/>");
        sw.WriteLine("   <Interior/>");
        sw.WriteLine("   <Protection/>");
        sw.WriteLine("  </Style>");
        sw.WriteLine("  <Style ss:ID=\"s21\">");
        sw.WriteLine("   <Alignment ss:Vertical=\"Bottom\" ss:WrapText=\"1\"/>");
        sw.WriteLine("  </Style>");
        sw.WriteLine(" </Styles>");
        DataTable dt;
        int c = ds.Tables.Count;
        for (int i = 0; i < c; i++)
        {
            dt = ds.Tables[i];
            WriteDtExcelXml(ref sw, ref dt);
        }
        sw.WriteLine("</Workbook>");
        sw = null;
        sw.Close();
    }

    public static void ExportExcel(ref DataTable dt, string fp)
    {
        Fun.DeleteFile(fp);
        StreamWriter sw = new StreamWriter(fp, false);
        sw.WriteLine("<?xml version=\"1.0\"?>");
        sw.WriteLine("<?mso-application progid=\"Excel.Sheet\"?>");
        sw.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
        sw.WriteLine(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
        sw.WriteLine(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
        sw.WriteLine(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
        sw.WriteLine(" xmlns:html=\"http://www.w3.org/TR/REC-html40\">");
        sw.WriteLine(" <DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">");
        sw.WriteLine("  <Author>Automated Report Generator Example</Author>");
        sw.WriteLine(string.Format("  <Created>{0}T{1}Z</Created>", DateTime.Now.ToString("yyyy-mm-dd"), DateTime.Now.ToString("HH:MM:SS")));
        sw.WriteLine("  <Company>Matteo</Company>");
        sw.WriteLine("  <Version>11.6408</Version>");
        sw.WriteLine(" </DocumentProperties>");
        sw.WriteLine(" <ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">");
        sw.WriteLine("  <WindowHeight>8955</WindowHeight>");
        sw.WriteLine("  <WindowWidth>11355</WindowWidth>");
        sw.WriteLine("  <WindowTopX>480</WindowTopX>");
        sw.WriteLine("  <WindowTopY>15</WindowTopY>");
        sw.WriteLine("  <ProtectStructure>False</ProtectStructure>");
        sw.WriteLine("  <ProtectWindows>False</ProtectWindows>");
        sw.WriteLine(" </ExcelWorkbook>");
        sw.WriteLine(" <Styles>");
        sw.WriteLine("  <Style ss:ID=\"Default\" ss:Name=\"Normal\">");
        sw.WriteLine("   <Alignment ss:Vertical=\"Bottom\"/>");
        sw.WriteLine("   <Borders/>");
        sw.WriteLine("   <Font/>");
        sw.WriteLine("   <Interior/>");
        sw.WriteLine("   <Protection/>");
        sw.WriteLine("  </Style>");
        sw.WriteLine("  <Style ss:ID=\"s21\">");
        sw.WriteLine("   <Alignment ss:Vertical=\"Bottom\" ss:WrapText=\"1\"/>");
        sw.WriteLine("  </Style>");
        sw.WriteLine(" </Styles>");
        WriteDtExcelXml(ref sw, ref dt);
        sw.WriteLine("</Workbook>");
        sw.Close();
        sw = null;
    }

    public static void WriteDtExcelXml(ref StreamWriter sw, ref DataTable dt)
    {
        int cc = dt.Columns.Count;
        int rc = dt.Rows.Count;
        int i = 0;
        sw.WriteLine(" <Worksheet ss:Name=\"" + (dt.TableName == "" ? "default" : dt.TableName) + "\">");
        sw.WriteLine(string.Format("  <Table ss:ExpandedColumnCount=\"{0}\" ss:ExpandedRowCount=\"{1}\" x:FullColumns=\"1\"", cc.ToString(), Convert.ToString(rc + 1)));
        sw.WriteLine("   x:FullRows=\"1\">");
        sw.WriteLine("<Row>");
        for (i = 0; i < cc; i++)
        {
            sw.Write("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">");
            sw.Write(dt.Columns[i].ColumnName);
            sw.WriteLine("</Data></Cell>");
        }
        sw.WriteLine("</Row>");
        foreach (DataRow dr in dt.Rows)
        {
            sw.WriteLine("<Row>");
            for (i = 0; i < cc; i++)
            {
                sw.Write("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">");
                sw.Write(dr[i].ToString());
                sw.WriteLine("</Data></Cell>");
            }
            sw.WriteLine("</Row>");
        }
        sw.WriteLine("  </Table>");
        sw.WriteLine("  <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
        sw.WriteLine("   <Selected/>");
        sw.WriteLine("   <Panes>");
        sw.WriteLine("    <Pane>");
        sw.WriteLine("     <Number>3</Number>");
        sw.WriteLine("     <ActiveRow>1</ActiveRow>");
        sw.WriteLine("    </Pane>");
        sw.WriteLine("   </Panes>");
        sw.WriteLine("   <ProtectObjects>False</ProtectObjects>");
        sw.WriteLine("   <ProtectScenarios>False</ProtectScenarios>");
        sw.WriteLine("  </WorksheetOptions>");
        sw.WriteLine(" </Worksheet>");
    }

    public static int GetRowsCount(string tab, string col, string v, bool b)
    {
        string sql = "";
        if (b)
        {
            sql = "select count(*) as znum from " + tab + " where " + col + "=" + v;
        }
        else
        {
            sql = "select count(*) as znum from " + tab + " where " + col + "='" + v.Replace("'", "''") + "'";
        }
        int c = Convert.ToInt32(Fun.GetField(sql, "znum"));
        return c;
    }

    public static bool CheckTable(ref DataTable dt, params string[] cols)
    {
        int c = dt.Columns.Count;
        bool r = true;
        foreach (string col in cols)
        {
            bool b = false;
            for (int i = 0; i < c; i++)
            {
                if (col.ToLower().Trim() == dt.Columns[i].ColumnName.Trim().ToLower())
                {
                    b = true;
                    break;
                }
            }
            r = r && b;
        }
        return r;
    }

    public static ArrayList GetMultiStr(ref DataTable dt, string col)
    {
        ArrayList ary = new ArrayList();
        int i = 0;
        int t = i;
        for (; i < dt.Rows.Count; i++)
        {
            string s1 = dt.Rows[i][col].ToString().Trim().ToLower();
            for (t = i + 1; t < dt.Rows.Count; t++)
            {
                string s2 = dt.Rows[t][col].ToString().Trim().ToLower();
                if (s1 == s2)
                {
                    ary.Add(s1);
                    break;
                }
            }
        }
        return ary;
    }

    public static string ConnectStrings(ArrayList ary, string s)
    {
        int c = ary.Count;
        string str = "";
        for (int i = 0; i < c; i++)
        {
            if (i == 0)
            {
                str = ary[i].ToString();
            }
            else
            {
                str = str + s + ary[i].ToString();
            }
        }
        return str;
    }

    public static bool ContainString(ArrayList a, string v)
    {
        foreach (object obj in a)
        {
            if (obj.ToString() == v)
            {
                return true;
            }
        }
        return false;
    }

    public static bool ContainString(DataTable dt,string c, string v)
    {
        foreach (DataRow dr in dt.Rows)
        {
            if (dr[c].ToString() == v)
            {
                return true;
            }
        }
        return false;
    }

    public static string GetStr(string str, string d)
    {
        return str.Trim() == "" ? d : str.Trim();
    }

    public static string GetStr(string str)
    {
        return Fun.GetStr(str, Params.SPACE);
    }

    public static string L(string _s)
    {
        return _s.Trim().Replace("'", "''");
    }

    public static int GetFirstSettingGuid()
    {
        string sql = "select top 1 Guid from Settings order by Guid asc";
        DataTable dt = Fun.CreateDt(sql);
        if (dt.Rows.Count < 1)
        {
            sql = "insert into Settings(Guid,SmtpEnabled) values("+Fun.Guid().ToString()+",0)";
            Fun.Execute(sql);
        }
        sql = "select top 1 Guid from Settings order by Guid asc";
        dt = Fun.CreateDt(sql);
        return Convert.ToInt32(dt.Rows[0][0]);
    }

    public static string JoinStrFromDt(string sql)
    {
        DataTable dt = Fun.CreateDt(sql);
        string s = "";
        foreach (DataRow dr in dt.Rows)
        {
            s = s + "," + dr[0].ToString().Trim();
        }
        return s.Trim(',');
    }

    public static string GenerateOrderSQL(ArrayList ary,bool hasWhere,bool hasAnd)
    {
        if (ary.Count == 0)
        {
            return "";
        }
        string s = ary[0].ToString();
        for (int i = 1; i < ary.Count; i++) 
        {
            s = s + " and " + ary[i].ToString();
        }
        if (hasWhere&&s.Trim()!="")
        {
            return " where " + s;
        }
        if (hasAnd && s.Trim() != "")
        {
            return " and " + s;
        }
        return s;
    }

    public static string GenerateOrderSQL(ArrayList ary)
    {
        return Fun.GenerateOrderSQL(ary, false, false);
    }

    public static void Refresh()
    {
        System.Web.HttpContext.Current.Response.Redirect(System.Web.HttpContext.Current.Request.RawUrl);
    }

    public static void Refresh(string tip)
    {
        System.Web.HttpContext.Current.Session.Add(Params.SystemError, tip);
        System.Web.HttpContext.Current.Response.Redirect(System.Web.HttpContext.Current.Request.RawUrl);
    }

    public static void Redirect(string url, string tip)
    {
        System.Web.HttpContext.Current.Session.Add(Params.SystemError, tip);
        System.Web.HttpContext.Current.Response.Redirect(url);
    }

    public static void DistributeExpertToStudent(int sg)
    {
        PaperMatch pm = new PaperMatch(sg);
        Thread matchThread = new Thread(new ThreadStart(pm.StartMatch));
        matchThread.Start();
        //pm.StartMatch();
    }

    public static bool ArrayContain(int[] ary, int i)
    {
        foreach (int ii in ary)
        {
            if (ii == i)
            {
                return true;
            }
        }
        return false;
    }

    public static void DistributeAllStudent()
    {
    }

    public static void DistributeAllStudentThread()
    {
        string sql = "select distinct UserGuid from Student where ExpertGuid=0 and PaperFlag<>0";
        DataTable dt = Fun.CreateDt(sql);
        foreach (DataRow dr in dt.Rows)
        {
            int sg = Convert.ToInt32(dr[0]);
            PaperMatch pm = new PaperMatch(sg);
            pm.StartMatch();
        }
    }

    public static bool IsProfilePage()
    {
        try
        {
            string[] ss = System.Web.HttpContext.Current.Request.Path.ToLower().Trim().Split('/');
            string pn = ss[ss.Length - 1];
            return pn == Params.ProfilePage;
        }
        catch
        {
            return true;
        }
    }

    public static void ClearWebSite(bool tea,bool doc,bool stu,bool email,bool pap,bool cat)
    {
        string sql;
        DataTable dt;
        if (tea)
        {
            sql = "select Guid from Users where UserType='" + LwUser.TeamType + "'";
            dt = Fun.CreateDt(sql);
            foreach (DataRow dr in dt.Rows)
            {
                Team.Delete(Convert.ToInt32(dr[0]));
            }
        }
        if (doc)
        {
            sql = "select Guid from Users where UserType='" + LwUser.DoctorType + "'";
            dt = Fun.CreateDt(sql);
            foreach (DataRow dr in dt.Rows)
            {
                Doctor.Delete(Convert.ToInt32(dr[0]));
            }
        }
        if (stu)
        {
            sql = "select Guid from Users where UserType='" + LwUser.StudentType + "'";
            dt = Fun.CreateDt(sql);
            foreach (DataRow dr in dt.Rows)
            {
                Student.Delete(Convert.ToInt32(dr[0]));
            }
        }
        if (email)
        {
            sql = "select Guid from Message";
            dt = Fun.CreateDt(sql);
            foreach (DataRow dr in dt.Rows)
            {
                Message.Delete(Convert.ToInt32(dr[0]));
            }
        }
        if (pap)
        {
            sql = "select Guid from Users where UserType='" + LwUser.StudentType + "'";
            dt = Fun.CreateDt(sql);
            foreach (DataRow dr in dt.Rows)
            {
                Paper.Delete(Convert.ToInt32(dr[0]));
            }
        }
        if (cat)
        {
            sql = "select Guid from Category";
            dt = Fun.CreateDt(sql);
            foreach (DataRow dr in dt.Rows)
            {
                Category.Delete(Convert.ToInt32(dr[0]));
            }
        }
    }
}
